using System;
using System.IO;
using System.Web;
using System.Text;
using System.Web.UI;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;

using RealDolmen.Controls;
using RealDolmen.SharePoint.Helpers;
using RealDolmen.SharePoint.ListFeatures.Elements;
using RealDolmen.Helpers;

[assembly: WebResource("RealDolmen.SharePoint.ListFeatures.Resources.Standard.ScriptLib.js", "application/x-javascript")]
namespace RealDolmen.SharePoint.ListFeatures.Controls
{
    public class ListFeatureStandardMenuItem : ListFeatureMenuItem
    {
        public override string Location
        {
            get { return "Microsoft.SharePoint.StandardMenu"; }
        }
        
        #region AddControl
        private StringBuilder stringBuilder;

        protected override void BeforeAddControls()
        {
            stringBuilder = new StringBuilder();

            ClientScriptManager cs = Page.ClientScript;

            // Add the library if necessary
            if (!cs.IsClientScriptBlockRegistered(GetType(), "LF.Standard.ScriptLib"))
            {
                string script = cs.GetWebResourceUrl(GetType(), "RealDolmen.SharePoint.ListFeatures.Resources.Standard.ScriptLib.js");
                script = string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>\n", script);

                cs.RegisterStartupScript(
                   GetType(), "LF.Standard.ScriptLib",
                   script, false);
            }
        }

        protected override void AddControl(Control ctrl, int index, ListFeatureCustomActionElement customAction)
        {
            if (ctrl != null)
            {
                Control parentCtrl = null;
                string groupId = customAction.GroupId;

                if (groupId.Contains("ActionsMenu"))
                {
                    parentCtrl = ControlHelper.GetControlDown<ActionsMenu>(Menu, false);
                }
                else if (groupId.Contains("SettingsMenu"))
                {
                    parentCtrl = ControlHelper.GetControlDown<SettingsMenu>(Menu, false);
                }


                if (parentCtrl != null)
                {
                    Control c = ControlHelper.GetControlDown<FeatureMenuTemplate>(parentCtrl, true);
                    CreateJsButton(ctrl, c.ClientID);
                }
            }
        }

        #region Core Javascript

        private void CreateJsSeparator(string parentid)
        {
            stringBuilder.AppendFormat("addStandardSeparator('{0}');\n", parentid);
        }

        private void CreateJsButton(Control control, string parentid)
        {
            StringBuilder sbControl = new StringBuilder();
            HtmlTextWriter writer = new HtmlTextWriter(new StringWriter(sbControl));
            control.RenderControl(writer);
            string strControl = sbControl.ToString().Replace("'", "\\'");

            stringBuilder.AppendLine("addStandardItem(");
            stringBuilder.AppendFormat("       '{0}',\n", strControl);
            stringBuilder.AppendFormat("       '{0}');\n", parentid);
        }
        #endregion // Core Javascript

        protected override void AfterAddControls()
        {
            string output = stringBuilder.ToString();

            if (output.Length > 8)
            {
                Page.ClientScript.RegisterStartupScript(
                   GetType(),
                   Guid.NewGuid().ToString(),
                   output, true);
            }
        }

        #endregion // AddControl

        #region BuildControl
        protected override Control BuildControl(ListFeatureCustomActionElement customAction)
        {
            ComputeShow(customAction.Rights);

            if (ShouldShow)
            {
                ListFeatureMenuControl control = new ListFeatureMenuControl();
                control.Text = customAction.ParsedTitle;
                control.Description = customAction.ParsedDescription;
                control.MenuGroupId = customAction.GroupId;

                string imageUrl = customAction.ImageUrl;
                if (string.IsNullOrEmpty(imageUrl))
                {
                    // imageUrl = "/_layouts/images/MenuNewItem.gif";
                }
                else
                {
                    if (imageUrl.IndexOf("/") == -1)
                    {
                        imageUrl = "/_layouts/images/" + imageUrl;
                    }
                }
                control.ImageUrl = imageUrl;


                string url = customAction.ParsedUrl;
                if (!string.IsNullOrEmpty(url))
                {
                    control.ClientOnClickNavigateUrl = url;
                }

                return control;
            }
            return null;
        } 
        #endregion // BuildControl

        #region Show
        private bool shouldShow = false;

        public bool ShouldShow
        {
            get { return shouldShow; }
        }

        private void ComputeShow(string rights)
        {
            if (!string.IsNullOrEmpty(rights))
            {
                shouldShow = RightsSensitiveVisibilityHelper.UserHasRights(
                        PermissionContext.CurrentList,
                        SPHelper.ParsePermissions(rights),
                        PermissionMode.All,
                        SPContext.Current.List);
            }
            else
                shouldShow = true;
        }
        #endregion // Show
    }

    public class ListFeatureMenuControl : Control
    {
        #region Properties
		private string imageUrl;

        public string ImageUrl
        {
            get { return imageUrl; }
            set { imageUrl = value; }
        }
        private string imageScript;

        public string ImageScript
        {
            get { return imageScript; }
            set { imageScript = value; }
        }

        private string clientOnClickScript;

        public string ClientOnClickScript
        {
            get { return clientOnClickScript; }
            set { clientOnClickScript = value; }
        }
        private string hiddenScript;

        public string HiddenScript
        {
            get { return hiddenScript; }
            set { hiddenScript = value; }
        }

        private string text;

        public string Text
        {
            get { return text; }
            set { text = value; }
        }

        private string textScript;

        public string TextScript
        {
            get { return textScript; }
            set { textScript = value; }
        }
        private string title;

        public string Title
        {
            get { return title; }
            set { title = value; }
        }
        private string description;

        public string Description
        {
            get { return description; }
            set { description = value; }
        }
        private string descriptionScript;

        public string DescriptionScript
        {
            get { return descriptionScript; }
            set { descriptionScript = value; }
        }
        private string menuGroupId = "800";

        public string MenuGroupId
        {
            get { return menuGroupId; }
            set { menuGroupId = value; }
        }

        private string m_clientOnClickNavigateUrl;
        public string ClientOnClickNavigateUrl
        {
            get
            {
                return this.m_clientOnClickNavigateUrl;
            }
            set
            {
                if (value == null)
                {
                    value = string.Empty;
                }
                string temp = value;
                temp = SPUtility.GetServerRelativeUrlFromPrefixedUrl(temp);

                // 05/06/2009: fixed javascript inclusion
                if (temp.ToLower().StartsWith("javascript:"))
                    this.ClientOnClickScript = temp;
                else
                    this.ClientOnClickScript = string.Format("window.location = '{0}';", JavascriptHelper.EscapeChar(temp, '\''));

                this.m_clientOnClickNavigateUrl = temp;
                this.ViewState["ClientOnClickNavigateUrl"] = temp;
            }
        }
	    #endregion // Properties

        #region Overrides
        protected override void Render(HtmlTextWriter output)
        {
            output.Write("<ie:menuitem id=\"");
            output.Write(Guid.NewGuid().ToString());
            output.Write("\" type=\"option\"");
            if (!string.IsNullOrEmpty(this.ImageUrl))
            {
                output.Write(" iconSrc=\"");
                output.Write(SPHttpUtility.HtmlUrlAttributeEncode(SPHttpUtility.UrlPathEncode(this.ImageUrl, false)));
                output.Write('"');
            }
            if (!string.IsNullOrEmpty(this.ImageScript))
            {
                output.Write(" iconScript=\"");
                output.Write(HttpUtility.HtmlEncode(this.ImageScript));
                output.Write('"');
            }
            if (!string.IsNullOrEmpty(this.ClientOnClickScript))
            {
                output.Write(" onMenuClick=\"");
                output.Write(HttpUtility.HtmlEncode(this.ClientOnClickScript));
                output.Write('"');
            }
            if (!string.IsNullOrEmpty(this.HiddenScript))
            {
                output.Write(" hidden=\"");
                output.Write(HttpUtility.HtmlEncode(this.HiddenScript));
                output.Write('"');
            }
            if (!string.IsNullOrEmpty(this.Text))
            {
                output.Write(" text=\"");
                output.Write(HttpUtility.HtmlEncode(this.Text));
                output.Write('"');
            }
            if (!string.IsNullOrEmpty(this.TextScript))
            {
                output.Write(" textScript=\"");
                output.Write(HttpUtility.HtmlEncode(this.TextScript));
                output.Write('"');
            }
            if (!string.IsNullOrEmpty(this.Title))
            {
                output.Write(" title=\"");
                output.Write(HttpUtility.HtmlEncode(this.Title));
                output.Write('"');
            }
            if (!string.IsNullOrEmpty(this.Description))
            {
                output.Write(" description=\"");
                output.Write(HttpUtility.HtmlEncode(this.Description));
                output.Write('"');
            }
            /*
            if (this.Page.IsCallback)
            {
                output.Write(" callbackitem=\"true\"");
            }
             */
            if (!string.IsNullOrEmpty(this.DescriptionScript))
            {
                output.Write(" descriptionScript=\"");
                output.Write(HttpUtility.HtmlEncode(this.DescriptionScript));
                output.Write('"');
            }
            if (!string.IsNullOrEmpty(this.MenuGroupId))
            {
                output.Write(" menuGroupId=\"");
                output.Write(this.MenuGroupId);
                output.Write("\"");
            }
            output.Write('>');
            output.Write("</ie:menuitem>");
        } 
        #endregion // Overrides
    }
}